package netty.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import netty.handler.ClientHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class NettyClient {

    private static final Logger log = LoggerFactory.getLogger(NettyClient.class.getSimpleName());

    public static void main(String[] args) throws InterruptedException {
        new NettyClient().start("127.0.0.1", 8080);
    }

    public void start(String host, int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            log.info("初始化Bootstrap");
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    /*
                     与服务端不同的是，客户端每一个请求就可以看做是一个Channel，所以不用像服务端那样有一个Channel来接收请求，
                     直接把ChannelHandler添加到该连接的Channel上即可
                      */
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            log.info("请求Channel创建完成");
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect().sync();
            log.info("Channel阻塞在关闭处");
            future.channel().closeFuture().sync();
            log.info("Channel已关闭");
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
